<template>
  <view class="page">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-bar-left" @click="handleBack">
        <uni-icons type="left" size="20" color="#333"/>
      </view>
      <view class="nav-bar-title">
        {{ orderInfo.paid ? '预约成功' : '待支付' }}
      </view>
    </view>

    <!-- 成功提示 -->
    <view class="success-container" v-if="orderInfo.paid">
      <view class="success-icon">
        <uni-icons type="checkmarkempty" size="64" color="#07c160"/>
      </view>
      <view class="success-title">预约成功</view>
      <view class="success-desc">您已成功预约医生门诊</view>
    </view>

    <!-- 订单信息 -->
    <view class="order-card">
      <view class="section-title">预约信息</view>
      
      <view class="info-row">
        <text class="label">医生姓名</text>
        <text class="value">{{ orderInfo.doctorName }}</text>
      </view>
      
      <view class="info-row">
        <text class="label">科室</text>
        <text class="value">{{ orderInfo.deptName }}</text>
      </view>
      
      <view class="info-row">
        <text class="label">就诊日期</text>
        <text class="value">{{ orderInfo.appointmentDate }}</text>
      </view>
      
      <view class="info-row">
        <text class="label">就诊时间</text>
        <text class="value">{{ timeSlots[Number(orderInfo.timeSlot) - 1] }}</text>
      </view>
      
      <view class="info-row">
        <text class="label">就诊方式</text>
        <text class="value">{{ orderInfo.visitType }}</text>
      </view>
      
      <view class="info-row">
        <text class="label">支付金额</text>
        <text class="value price">¥{{ orderInfo.amount }}</text>
      </view>
      
      <view class="info-row">
        <text class="label">订单编号</text>
        <text class="value">{{ orderInfo.orderNo }}</text>
      </view>

      <view class="info-row" v-if="orderInfo.visitType === '视频问诊' || orderInfo.visitType === '图文问诊'">
        <text class="label">诊室链接</text>
        <text class="value link" @click="enterClinic">点击进入</text>
      </view>
    </view>
    
    <!-- 支付倒计时 -->
    <view class="countdown-card" v-if="!orderInfo.paid">
      <view class="section-title">支付倒计时</view>
      <view class="countdown-content">
        <text class="countdown-text">请在</text>
        <text class="countdown-time">{{ countdown }}</text>
        <text class="countdown-text">内完成支付</text>
      </view>
    </view>
    
    <!-- 就诊须知 -->
    <view class="notice-card">
      <view class="section-title">就诊须知</view>
      <view class="notice-content">
        <view class="notice-item" v-if="orderInfo.visitType === '门诊就医'">1. 请在就诊前15分钟到达医院，凭预约码在自助机或导诊台取号。</view>
        <view class="notice-item" v-if="orderInfo.visitType === '门诊就医'">2. 请携带有效证件（身份证、医保卡等）。</view>
        <view class="notice-item" v-if="orderInfo.visitType === '视频问诊'">1. 请在预约时间前5分钟进入在线诊室，确保网络畅通。</view>
        <view class="notice-item" v-if="orderInfo.visitType === '图文问诊'">1. 您可以随时发送文字、图片与医生沟通。</view>
        <view class="notice-item">{{ noticeByVisitType }}</view>
        <view class="notice-item">3. 如需取消预约，请提前4小时操作，否则将影响您的预约记录。</view>
        <view class="notice-item">4. 如有疑问，请联系客服电话：400-123-4567。</view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <template v-if="!orderInfo.paid">
        <view class="btn-row">
          <button class="btn primary-btn" @click="handlePay">立即支付</button>
          <button class="btn secondary-btn" @click="viewDetail">查看订单详情</button>
        </view>
        <button class="btn cancel-btn" @click="handleCancel">取消预约</button>
      </template>
      <template v-else>
        <button class="btn primary-btn" @click="viewDetail">查看订单详情</button>
      </template>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { apiBaseUrl } from '../../../config/api'
declare const uni: any;
declare const getCurrentPages: () => any[];

// 订单信息
const orderInfo = ref({
  doctorName: '',
  deptName: '',
  appointmentDate: '',
  timeSlot: '',
  visitType: '',
  amount: 0,
  orderNo: '',
  orderId: '',
  paid: false
})

// 时间段列表
const timeSlots = [
  '08:00~08:30', '08:30~09:00', '09:00~09:30', '09:30~10:00',
  '10:00~10:30', '10:30~11:00', '11:00~11:30', '11:30~12:00',
  '13:00~13:30', '13:30~14:00', '14:00~14:30', '14:30~15:00',
  '15:00~15:30', '15:30~16:00', '16:00~16:30'
]

// 倒计时
const countdown = ref('10:00')
let countdownTimer: NodeJS.Timeout | null = null
const totalSeconds = 10 * 60 // 10分钟
// 添加一个标志变量，防止重复启动倒计时
const countdownStarted = ref(false)

// 根据问诊方式提供不同的提示文案
const noticeByVisitType = computed(() => {
  if (orderInfo.value.visitType === '视频问诊') {
    return '2. 请确保您的设备摄像头和麦克风正常工作。';
  } else if (orderInfo.value.visitType === '图文问诊') {
    return '2. 请尽量描述清楚症状，必要时可上传图片辅助诊断。';
  } else {
    return '3. 如有检查报告，请随身携带。';
  }
});

// 获取订单详情
const getOrderDetail = async (orderId) => {
  console.log('开始获取订单详情')
  try {
    uni.showLoading({
      title: '加载中'
    })
    
    const res = await uni.request({
      url: apiBaseUrl + '/patient/appointment/order/detail',
      method: 'POST',
      data: {
        orderId: orderId
      }
    })
    
    console.log('订单详情接口返回:', res)
    uni.hideLoading()
    
    if (res.statusCode === 200 && res.data.code === 200) {
      orderInfo.value = res.data.result
      console.log('更新后的订单信息:', orderInfo.value)
      // 如果订单未支付且倒计时未启动，才启动倒计时
      if (!orderInfo.value.paid && !countdownStarted.value) {
        startCountdown()
      }
    } else {
      uni.showToast({
        title: '获取订单信息失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '获取订单信息失败',
      icon: 'none'
    })
    console.error('获取订单详情失败:', error)
  }
}

// 启动倒计时
const startCountdown = () => {
  // 防止重复启动倒计时
  if (countdownStarted.value) {
    return
  }
  
  // 先清除现有的倒计时器
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  
  let remainingSeconds = totalSeconds
  countdownStarted.value = true
  
  countdownTimer = setInterval(() => {
    remainingSeconds--
    
    if (remainingSeconds <= 0) {
      clearInterval(countdownTimer!)
      countdownTimer = null
      // 倒计时结束，自动取消订单
      handleCancel()
      return
    }
    
    const minutes = Math.floor(remainingSeconds / 60)
    const seconds = remainingSeconds % 60
    countdown.value = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }, 1000)
}

// 模拟支付成功后端处理
const simulatePaymentSuccess = async (orderId) => {
  try {
    // 调用后端接口更新订单状态为已支付
    const res = await uni.request({
      url: apiBaseUrl + '/patient/appointment/order/paySuccess/callback',
      method: 'POST',
      data: {
        orderId: orderId,
        status: 'SUCCESS',
        tradeNo: 'MOCK_' + Date.now(),
        payTime: new Date().toISOString()
      }
    })
    
    if (res.statusCode !== 200 || res.data.code !== 200) {
      console.error('支付状态更新失败:', res.data)
      throw new Error('支付状态更新失败')
    }
    
    // 等待一段时间确保后端处理完成
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    return res.data
  } catch (error) {
    console.error('模拟支付回调失败:', error)
    // 抛出异常以便调用方处理
    throw error
  }
}

// 处理支付
const handlePay = async () => {
  try {
    uni.showLoading({
      title: '获取支付参数中'
    })
    
    // 获取支付参数
    const res = await uni.request({
      url: apiBaseUrl + '/payment/wxpay/create',
      method: 'POST',
      data: {
        orderId: orderInfo.value.orderId,
        totalFee: orderInfo.value.amount * 100, // 微信支付以分为单位
        body: `${orderInfo.value.doctorName}医生挂号费`,
        openId: await getOpenId()
      }
    })
    
    uni.hideLoading()
    
    if (res.statusCode === 200 && res.data.code === 200) {
      const payParams = res.data.result
      
      // 开发环境使用模拟支付
      const useSimulatedPayment = true; // 设置为true强制使用模拟支付
      
      if (useSimulatedPayment) {
        try {
          // 模拟支付成功
          await simulatePaymentSuccess(orderInfo.value.orderId);
          
          // 更新订单状态
          orderInfo.value.paid = true
          
          // 清除倒计时
          if (countdownTimer) {
            clearInterval(countdownTimer)
            countdownTimer = null
            countdownStarted.value = false
          }
          
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
          
          // 延迟后跳转到订单详情页面，使用重定向而不是导航
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/index/orders/detail?orderId=${orderInfo.value.orderId}&fromCreate=true`,
              success: () => {
                console.log('支付后跳转至订单详情成功')
              },
              fail: (err) => {
                console.error('支付后跳转失败:', err)
              }
            })
          }, 1500)
        } catch (error) {
          console.error('支付处理失败:', error)
          uni.showToast({
            title: '支付处理失败，请稍后重试',
            icon: 'none'
          })
        }
        return
      }
      
      // 正式环境调用微信支付
      uni.requestPayment({
        ...payParams,
        timeStamp: payParams.timeStamp.toString(),
        success: async function() {
          try {
            // 支付成功
            await simulatePaymentSuccess(orderInfo.value.orderId);
            
            // 更新订单状态
            orderInfo.value.paid = true
            
            // 清除倒计时
            if (countdownTimer) {
              clearInterval(countdownTimer)
              countdownTimer = null
              countdownStarted.value = false
            }
            
            uni.showToast({
              title: '支付成功',
              icon: 'success'
            })
            
            // 延迟后跳转到订单详情页面，使用重定向而不是导航
            setTimeout(() => {
              uni.redirectTo({
                url: `/pages/index/orders/detail?orderId=${orderInfo.value.orderId}&fromCreate=true`,
                success: () => {
                  console.log('支付后跳转至订单详情成功')
                },
                fail: (err) => {
                  console.error('支付后跳转失败:', err)
                }
              })
            }, 1500)
          } catch (error) {
            console.error('支付处理失败:', error)
            uni.showToast({
              title: '支付处理失败，请稍后重试',
              icon: 'none'
            })
          }
        },
        fail: function(err) {
          console.log('支付失败:', err)
          if (err.errMsg !== 'requestPayment:fail cancel') {
            uni.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        }
      })
    } else {
      uni.showToast({
        title: '获取支付参数失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '支付失败',
      icon: 'none'
    })
    console.error('支付失败:', error)
  }
}

// 获取用户openid
const getOpenId = async () => {
  const openid = uni.getStorageSync('openId')
  if (openid) {
    return openid
  }
  
  try {
    const loginRes = await uni.login()
    const res = await uni.request({
      url: apiBaseUrl + '/user/wx/getOpenid',
      method: 'POST',
      data: {
        code: loginRes.code
      }
    })
    
    if (res.statusCode === 200 && res.data.code === 200) {
      const openid = res.data.result.openid
      uni.setStorageSync('openid', openid)
      return openid
    } else {
      throw new Error('获取openid失败')
    }
  } catch (error) {
    console.error('获取openid失败:', error)
    throw new Error('获取用户信息失败')
  }
}

// 取消预约
const handleCancel = async () => {
  try {
    uni.showLoading({
      title: '取消中'
    })
    
    const res = await uni.request({
      url: apiBaseUrl + '/patient/appointment/order/cancel',
      method: 'POST',
      data: {
        orderId: orderInfo.value.orderId
      }
    })
    
    uni.hideLoading()
    
    if (res.statusCode === 200 && res.data.code === 200) {
      // 重置倒计时标志
      if (countdownTimer) {
        clearInterval(countdownTimer)
        countdownTimer = null
        countdownStarted.value = false
      }
      
      uni.showToast({
        title: '订单已取消',
        icon: 'success'
      })
      
      // 返回首页
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }, 1500)
    } else {
      uni.showToast({
        title: '取消失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '取消失败',
      icon: 'none'
    })
    console.error('取消订单失败:', error)
  }
}

// 进入在线诊室
const enterClinic = () => {
  if (orderInfo.value.visitType === '视频问诊') {
    uni.navigateTo({
      url: `/pages/index/clinic/video?orderId=${orderInfo.value.orderId}`
    })
  } else if (orderInfo.value.visitType === '图文问诊') {
    uni.navigateTo({
      url: `/pages/index/clinic/chat?orderId=${orderInfo.value.orderId}`
    })
  }
}

// 查看订单详情
const viewDetail = () => {
  console.log('点击查看订单详情按钮')
  console.log('当前页面实例:', getCurrentPages())
  console.log('跳转前的订单信息:', orderInfo.value)
  
  if (!orderInfo.value.orderId) {
    console.log('订单ID不存在，重新获取订单信息')
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage.$page?.options || {}
    
    if (options.orderId) {
      console.log('从页面参数获取到orderId:', options.orderId)
      getOrderDetail(options.orderId)
      return
    }
    
    uni.showToast({
      title: '订单信息不完整',
      icon: 'none'
    })
    return
  }
  
  const url = `/pages/index/orders/detail?orderId=${orderInfo.value.orderId}&fromCreate=true`
  console.log('跳转URL:', url)
  
  // 使用重定向而不是普通跳转
  uni.redirectTo({
    url: url,
    success: () => {
      console.log('跳转成功')
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      })
    }
  })
}

// 返回首页
const goHome = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

// 返回上一页
const handleBack = () => {
  goHome()
}

// 页面加载
onLoad((options) => {
  console.log('预约成功页面加载，参数:', options)
  if (options?.orderId) {
    console.log('获取到orderId:', options.orderId)
    // 在onLoad中保存订单ID，但不立即请求详情，交给onMounted处理
    orderInfo.value.orderId = options.orderId
  } else {
    console.log('未获取到orderId，当前页面实例:', getCurrentPages())
  }
})

// 页面显示
onShow(() => {
  console.log('预约成功页面显示')
  console.log('当前订单信息:', orderInfo.value)
  // onShow时，如果已经获取过订单信息且倒计时已经启动，则不重复获取
  if (!orderInfo.value.doctorName && orderInfo.value.orderId) {
    console.log('页面显示时需要重新获取订单详情')
    getOrderDetail(orderInfo.value.orderId)
  }
})

onMounted(() => {
  // 在组件挂载时获取订单详情
  if (orderInfo.value.orderId) {
    console.log('组件挂载时获取订单详情')
    getOrderDetail(orderInfo.value.orderId)
  } else {
    // 尝试从路由参数获取orderId
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const options = currentPage.options || {}
    
    if (options?.orderId) {
      console.log('组件挂载时从路由参数获取订单ID:', options.orderId)
      orderInfo.value.orderId = options.orderId
      getOrderDetail(options.orderId)
    }
  }
})

onUnmounted(() => {
  // 组件卸载时清除倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
    countdownStarted.value = false
  }
})
</script>

<style>
.page {
  min-height: 100vh;
  background: #f5f8ff;
  padding-bottom: env(safe-area-inset-bottom);
  padding-top: calc(44px + env(safe-area-inset-top) + 88rpx);
}

.nav-bar {
  position: fixed;
  top: calc(44px + env(safe-area-inset-top));
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  z-index: 100;
}

.nav-bar-left {
  width: 44rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
}

.nav-bar-title {
  flex: 1;
  text-align: center;
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
}

.success-container {
  margin: 20rpx;
  padding: 40rpx 30rpx;
  background: #fff;
  border-radius: 12rpx;
  text-align: center;
}

.success-icon {
  margin-bottom: 20rpx;
}

.success-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 12rpx;
}

.success-desc {
  font-size: 28rpx;
  color: #666;
}

.order-card, .notice-card {
  margin: 20rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 12rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
  border-left: 4rpx solid #2979ff;
  padding-left: 16rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.info-row:last-child {
  border-bottom: none;
}

.label {
  font-size: 28rpx;
  color: #666;
}

.value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.price {
  color: #f56c6c;
}

.link {
  color: #2979ff;
  text-decoration: underline;
}

.notice-content {
  margin-top: 12rpx;
}

.notice-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 12rpx;
}

.countdown-card {
  margin: 20rpx;
  padding: 30rpx;
  background: #fff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.countdown-content {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20rpx;
}

.countdown-text {
  font-size: 28rpx;
  color: #666;
}

.countdown-time {
  font-size: 36rpx;
  font-weight: 600;
  color: #f56c6c;
  margin: 0 12rpx;
  font-family: monospace;
}

.bottom-buttons {
  margin: 40rpx 20rpx;
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  width: 100%;
  box-sizing: border-box;
  padding: 0 20rpx;
}

.btn-row {
  display: flex;
  gap: 20rpx;
  width: 100%;
}

.btn {
  height: 96rpx;
  line-height: 96rpx;
  border-radius: 48rpx;
  font-size: 34rpx;
  text-align: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

.btn-row .btn {
  flex: 1;
  width: auto;
}

.cancel-btn {
  width: 100%;
}

.primary-btn {
  background: linear-gradient(135deg, #2979ff, #1a56ff);
  color: #fff;
  box-shadow: 0 6rpx 16rpx rgba(41, 121, 255, 0.3);
  font-weight: 500;
}

.primary-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 3rpx 8rpx rgba(41, 121, 255, 0.3);
}

.secondary-btn {
  background: #fff;
  color: #333;
  border: 2rpx solid #e8e8e8;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  font-weight: 500;
}

.secondary-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  background: #f8f8f8;
}

.cancel-btn {
  background: #fff;
  color: #f56c6c;
  border: 2rpx solid #f56c6c;
  box-shadow: 0 4rpx 12rpx rgba(245, 108, 108, 0.1);
  font-weight: 500;
}

.cancel-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 6rpx rgba(245, 108, 108, 0.1);
  background: #fff5f5;
}
</style> 